<template>
  <div v-if="words.length > 0" class="container">
    <h2 style="font-size: 40px;">{{ words[currentIndex].word }}</h2>
    <p style="margin-bottom: 20px;">{{ words[currentIndex].description }}</p>
    <ul>
      <li v-for="(option, index) in words[currentIndex].options" :key="index" @click="checkAnswer(option)"
        :class="{ correct: isCorrect && selectedOption === option, wrong: isWrong && selectedOption === option }">
        {{ option }}
      </li>
    </ul>
  </div>
  <div v-else>
    <p>正在加载单词...</p>
  </div>

  <wordDrawerTop :key="selectedWord" :word="selectedWord" :show="showDrawer" />
</template>

<script setup>
import { ref, computed, onMounted, nextTick } from 'vue';
import wordDrawerTop from "../../components/wordDrawerTop.vue";
const CACHE_KEY = 'excelDataCache';
const words = ref([]);
const currentIndex = ref(0);
const isWrong = ref(false);
const isCorrect = ref(false);
const selectedOption = ref(null);

// 加载缓存数据
const loadFromCache = () => {
  const cached = localStorage.getItem(CACHE_KEY);
  if (cached) {
    try {
      const parsedCache = JSON.parse(cached);
      const decryptedData = JSON.parse(parsedCache.data); // 解析 JSON 数据
      console.log('从缓存中读取数据:', decryptedData);

      // 处理实际数据
      const actualData = decryptedData?.["[[Target]]"] || decryptedData;
      if (Array.isArray(actualData)) {
        words.value = actualData
          .filter(item => Array.isArray(item) && item.length >= 3)
          .map(item => ({
            word: item[0],
            meaning: item[2],
            description: `发音：${item[1]} 释义：${item[2]}`,
            options: generateOptions(actualData, item[2])
          }));
      } else {
        console.error("缓存数据不是数组:", actualData);
      }
    } catch (error) {
      console.error('数据解析错误:', error);
    }
  }
};

// 生成选项，确保正确答案包含在内
const generateOptions = (data, correctMeaning) => {
  const options = new Set([correctMeaning]);
  while (options.size < 4) {
    const randomItem = data[Math.floor(Math.random() * data.length)];
    if (Array.isArray(randomItem) && randomItem.length >= 3) {
      options.add(randomItem[2]);
    }
  }
  return Array.from(options).sort(() => Math.random() - 0.5);
};

// 计算当前单词
const currentWord = computed(() => words.value[currentIndex.value]);


// detail drawer
const selectedWord = ref("");
const showDrawer = ref(false);

const openDrawer = async (word) => {
  if (showDrawer.value) {
    showDrawer.value = false;
    await nextTick(); // 等待 DOM 更新，确保 Drawer 彻底关闭
  }

  selectedWord.value = word;
  setTimeout(() => {
    showDrawer.value = true;
  }, 10); // 短暂延迟，让 Vue 先处理关闭后再打开
};



// 检查答案
const checkAnswer = (option) => {
  selectedOption.value = option;
  if (option === currentWord.value.meaning) {
    isCorrect.value = true;
    setTimeout(() => {
      nextWord();
      isCorrect.value = false;
    }, 500);
  } else {

    isWrong.value = true;
    setTimeout(() => {
      isWrong.value = false;
      openDrawer(words.value[currentIndex.value].word)
    }, 100);
  }
  // console.log(words.value[currentIndex.value].word);

};

// 切换到下一个单词
const nextWord = () => {
  if (currentIndex.value < words.value.length - 1) {
    currentIndex.value++;
    isWrong.value = false;
    selectedOption.value = null;
  } else {
    alert("游戏结束！");
    currentIndex.value = 0;
  }
};

// 组件挂载时加载缓存数据
onMounted(() => {
  loadFromCache();
});




import { inject } from "vue";

const theme = inject("theme");
const setTheme = (newTheme) => {
  theme.value = newTheme; // 更新全局主题
};
</script>

<style lang="scss" scoped>
.container {
  /* position: relative; */
  width: 100%;
  height: 100vh;
  color: var(--btn-text);
  background: linear-gradient(var(--bg-color-deg), var(--bg-color-change1), var(--bg-color-change2), var(--bg-color-change3));
  background-size: 400% 400%;
  animation: gradientAnimation 10s infinite alternate ease-in-out;
  transition: background 1s, color 1s;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;

  @keyframes gradientAnimation {
    0% {
      background-position: 0% 50%;
    }

    50% {
      background-position: 100% 50%;
    }

    100% {
      background-position: 0% 50%;
    }

  }
}


@keyframes shake {
  0% {
    transform: translateX(0);
  }

  25% {
    transform: translateX(-5px);
  }

  50% {
    transform: translateX(5px);
  }

  75% {
    transform: translateX(-5px);
  }

  100% {
    transform: translateX(0);
  }
}

.quiz-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: var(--btn-bg);
  font-family: Arial, sans-serif;
}

.word-display {
  // background: #ffffff;
  background-color: var(--btn-bg);
  padding: 20px 40px;
  border-radius: 10px;
  box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  text-align: center;
  transition: transform 0.3s ease-in-out;
}

.word-meaning {
  font-size: 14px;
  // color: #666;
  margin-top: 5px;
}

.options {
  list-style: none;
  padding: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

li {
  background-color: var(--btn-bg);
  width: 250px;
  padding: 15px 25px;
  // border: 2px solid #000;
  cursor: pointer;
  border-radius: 8px;
  // background: white;
  transition: background 0.3s, transform 0.2s;
  box-shadow: 2px 2px 8px var(--border-color);
  text-align: center;
  margin-top: 2vh;
}

li:hover {
  // background: #e0e0e0;
  transform: scale(1.05);
}

li.wrong {
  background-color: rgb(146, 58, 58);
  // color: white;
  animation: shake 0.5s;
}

li.correct {
  background-color: rgb(79, 109, 79);
  // color: white;
  // animation: fadeOut 0.1s forwards;
}

@keyframes shake {

  0%,
  100% {
    transform: translateX(0);
  }

  25% {
    transform: translateX(-5px);
  }

  50% {
    transform: translateX(5px);
  }

  75% {
    transform: translateX(-5px);
  }
}

@keyframes fadeOut {
  0% {
    opacity: 1;
  }

  100% {
    opacity: 0;
  }
}
</style>
